<template>
  <!-- 当前节点 -->
  <tr :class="['zdp-treetable__row', { 'zdp-treetable__row--expanded': node.expanded }]">
    <!-- 每一列 -->
    <td v-for="(column, colIndex) in columns"
        :key="colIndex"
        :class="column.className"
        :style="{borderBottom: '1px solid #eee'}"
    >
      <!-- 第一列：展开/折叠图标和节点名称 -->
      <template v-if="colIndex === 0">
        <div :style="{ paddingLeft: `${level * 25}px` }">
          <span
              v-if="node.children && node.children.length"
              class="zdp-treetable__toggle"
              @click="toggleExpand(node)"
          >
          {{ node.expanded ? '▼' : '▶' }}
        </span>
          <span class="zdp-treetable__label">
          {{ node.label }}
        </span>
        </div>
      </template>
      <!-- 其他列：显示对应数据 -->
      <template v-else>
        {{ node[column.prop] }}
      </template>
    </td>
    <!-- 操作列 -->
    <td
        v-if="hasActions"
        class="zdp-treetable__actions"
        :style="{borderBottom: '1px solid #eee'}"
    >
      <template v-if="$slots.actions">
        <div style="padding: 10px 5px; display: flex; gap: 5px;">
          <slot name="actions" :node="node"></slot>
        </div>
      </template>
    </td>
  </tr>

  <!-- 子节点 -->
  <template v-if="node.children && node.expanded">
    <TreeTableRow
        v-for="(child, index) in node.children"
        :key="index"
        :node="child"
        :columns="columns"
        :level="level + 1"
        @toggle="toggleExpand"
    >
      <!-- 操作列插槽 -->
      <template v-if="$slots.actions" #actions="{ node }">
        <slot name="actions" :node="node"></slot>
      </template>
    </TreeTableRow>
  </template>
</template>

<script setup>
import {defineProps, defineEmits, computed, useSlots} from 'vue';

// 定义 Props
const props = defineProps({
  node: {
    type: Object,
    required: true,
  },
  columns: {
    type: Array,
    required: true,
  },
  level: {
    type: Number,
    default: 0,
  },
});

// 定义 Emits
const emit = defineEmits(['toggle']);

// 判断是否有操作列插槽
const hasActions = computed(() => !!useSlots().actions);

// 切换节点展开/折叠状态
const toggleExpand = (node) => {
  emit('toggle', node);
};
</script>

<style scoped>
.zdp-treetable__row {
  transition: background-color 0.3s ease;
}

.zdp-treetable__row:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.zdp-treetable__toggle {
  margin-right: 8px;
  cursor: pointer;
  color: #409eff;
}

.zdp-treetable__label {
  font-weight: bold;
}

.zdp-treetable__actions {
  display: flex;
  gap: 8px;
}

.zdp-treetable__action-btn {
  padding: 4px 8px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.zdp-treetable__action-btn:hover {
  background-color: #66b1ff;
}
</style>